﻿using System;
using System.Data;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using VanTaiBLL;
using VanTaiProperty;
using System.Net.Mail;
using Roles;
namespace VanTaiTMS.Page
{
    public partial class DeNghiSuaChua : System.Web.UI.Page
    {
        #region[Define]

        private static bool _flag;
        private readonly clsTMRepair_SuggestionBusiness _clsDeNghiSuaChua = new clsTMRepair_SuggestionBusiness();
        private readonly clsTMVehicleBusiness _clsXe = new clsTMVehicleBusiness();
        private readonly clsTMRepairMaterialsBusiness _clsVatTuSuaChua = new clsTMRepairMaterialsBusiness();
        private readonly clsTMSymbolRepairMaterialsBusiness _clsLoaiVatTuSuaChua = new clsTMSymbolRepairMaterialsBusiness();
        private readonly clsTMNationalBusiness _clsQuocGia = new clsTMNationalBusiness();
        private readonly clsTMDepartmentBusiness _clsPhongBan = new clsTMDepartmentBusiness();
        private readonly TMMAIL_CONFIG_BusinessLogic _clsMailConfig = new TMMAIL_CONFIG_BusinessLogic();
        protected string StrAlert = "";
        public string SuggestionList = "";
        private DataTable _dtAutoComplete;
        private DataTable _dtDeNghiSuaChua;
        private DataTable _dtDeNghiSuaChuaEdit;
        private DataTable _dtSearch;

        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermisstion();
            Autocomplete();
            if (!IsPostBack)
            {
                BindGridDr();
                BindGridDeNghiSuaChua();
            }
        }
        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            _flag = true;
            lbThongBaoLoi.Text = "";
            txtChungTu.Enabled = true;
            ClearTextbox();
            txtChungTu.Text = "MT000" + MaTuDong();
            OpenDialog("#denghisuachua");
            imgSave.ToolTip = "Thêm mới";
            upNewUpdatePanel.Update();
            imgSave.Visible = true;
        }
        protected void cmdEdit_Click(object sender, EventArgs e)
        {
            lbThongBaoLoi.Text = "";
            txtChungTu.Enabled = false;
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                var chkView = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                if (chkView != null)
                {
                    if (chkView.Checked)
                    {
                        var dataKey = ListViewAll.DataKeys[i];
                        if (dataKey != null)
                            BindGridDeNghiSuaChuaEdit(Convert.ToInt32(dataKey.Value.ToString()));
                        OpenDialog("#denghisuachua");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        _flag = false;
                    }
                }
            }
        }
        protected void cmdDel_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                var chkhide = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                if (chkhide != null)
                {
                    if (chkhide.Checked)
                    {
                        try
                        {
                            clsTMRepair_SuggestionBusiness.DeleteTMRepair_Suggestion(int.Parse(ListViewAll.DataKeys[i].Value.ToString()));
                        }
                        catch (Exception)
                        {
                            lbThongBaoXoa.Text = "Mẫu tin này vẩn còn tồn tại.Không thể xoá !";
                            OpenDialog("#thongbaoxoa");
                            upDatePanelThongBaoXoa.Update();
                            cmdAgree.Visible = false;
                            cmdClose.Text = "Đóng lại";
                        }
                    }
                }
            }
        }
        protected void cmdSerach_Click(object sender, EventArgs e)
        {
            if (txtSearch.Text == "")
            {
                StrAlert += "<div class='alert alert-warning'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Vui lòng nhập vào từ khoá để tìm kiếm !";
                StrAlert += "</div>";
            }
            else
            {
                Search(txtSearch.Text);
            }
        }
        protected void cmdRefesh_Click(object sender, EventArgs e)
        {
            txtSearch.Text = "";
            txtDateBeGin.Text = "";
            txtDateEnd.Text = "";
            drFilterSoXe.SelectedIndex = -1;
            BindGridDeNghiSuaChua();
        }
        protected void cmdDuyet_Click(object sender, EventArgs e)
        {
            //-------------------------------------------
            try
            {
                for (int i = 0; i < ListViewAll.Items.Count; i++)
                {
                    var chkView = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                    if (chkView != null)
                    {
                        if (chkView.Checked)
                        {
                            var dataKey = ListViewAll.DataKeys[i];
                            if (dataKey != null)
                                BindGridEmail(Convert.ToInt32(dataKey.Value.ToString()));
                            OpenDialog("#duyetdenghisuachua");
                            upDatePanelDuyetLenh.Update();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void cmdFilter_Click(object sender, EventArgs e)
        {
            txtSearch.Text = "";
            drFilterSoXe.SelectedIndex = -1;
            BindGridDeNghiSuaChua();
        }
        //---------------button-popup---------------------
        protected void imgrefesh_Click(object sender, ImageClickEventArgs e)
        {
            BindGridDr();
        }
        protected void imgSave_Click(object sender, ImageClickEventArgs e)
        {
            if (txtChungTu.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào Chứng Từ Đề Nghị !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtNgay.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào ngày Đề Nghị !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drSoXe.SelectedValue == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn số xe !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drLoaiVatTuThayThe.SelectedValue == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn vật tư sữa chữa thay thế !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drKyHieuLoaiVatTu.SelectedValue == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn ký hiệu vật tư sữa chữa thay thế !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drQuocGia.SelectedValue == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn quốc gia !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtSoLuong.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào số lượng !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtDonGia.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào đơn giá !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtChungTu.Text != "" && txtNgay.Text != "" && drSoXe.SelectedValue != "-1" && drLoaiVatTuThayThe.SelectedValue != "-1" && drKyHieuLoaiVatTu.SelectedValue != "-1" && drQuocGia.SelectedValue != "-1" && txtSoLuong.Text != "" && txtDonGia.Text != "")
            {
                Insert();
            }
        }
        protected void cmdAgree_Click(object sender, EventArgs e)
        {
            
        }
        protected void ImgXetDuyet_Click(object sender, ImageClickEventArgs e)
        {
            BrowserNv();
        }
        protected void ImgRefeshDuyet_Click(object sender, ImageClickEventArgs e)
        {

        }
        protected void cmdClose_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbaoxoa");
        }
        protected void cmdCloseThongBao_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbao");
        }
        //-------------list-view-----------------------
        protected void ListViewAll_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                HttpCookie cookie = Request.Cookies["UserLogin"];
                bool Edit = SecurityServices.HasPermisstion(StringContent.QuanLySuaChuaThayThe, int.Parse(cookie["RolesID"]), TypeaAudit.Edit);
                lbThongBaoLoi.Text = "";
                txtChungTu.Enabled = false;
                if (e.CommandName == "Accept")
                {
                    if (Edit == false)
                    {
                        imgSave.Visible = false;
                        string senderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                        BindGridDeNghiSuaChuaEdit(int.Parse(senderId));
                        OpenDialog("#denghisuachua");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        _flag = false;
                    }
                    else
                    {
                        imgSave.Visible = true;
                        string senderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                        BindGridDeNghiSuaChuaEdit(int.Parse(senderId));
                        OpenDialog("#denghisuachua");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        _flag = false;
                    }
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void ListViewAll_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                var linkName = (LinkButton)e.Item.FindControl("linkTenDeNghiSuaChua");
                string jsDouble = ClientScript.GetPostBackClientHyperlink(linkName, "");
                linkName.Attributes["ondblclick"] = jsDouble;
                linkName.Attributes["onclick"] = "return false;";
            }
        }
        //-----------pagger-----------------------
        protected void DataPagerListAll_PreRender(object sender, EventArgs e)
        {
            DataPagerListAll.PageSize = 17;
            BindGridDeNghiSuaChua();
        }
        //---------Check-all--------------
        protected void chkCheckAll_CheckedChanged(object sender, EventArgs e)
        {
        }
        protected void LinkThemNhanhTinh_Click(object sender, EventArgs e)
        {
            OpenDialog("#ThemNhanhTinh");
        }
        protected void drSoXe_SelectedIndexChanged(object sender, EventArgs e)
        {
            drTaiXe.SelectedValue = drSoXe.SelectedValue;
            drNhomXe.SelectedValue = drSoXe.SelectedValue;
        }
        protected void drFilterSoXe_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtDateBeGin.Text = "";
            txtDateEnd.Text = "";
            txtSearch.Text = "";
            BindGridDeNghiSuaChua();
        }
        protected void txtSearch_TextChanged(object sender, EventArgs e)
        {
            txtDateBeGin.Text = "";
            txtDateEnd.Text = "";
            drFilterSoXe.SelectedIndex = -1;
        }
        protected void LinkThemNhanhSoXe_Click(object sender, EventArgs e)
        {
            OpenDialog("#ThemNhanhXe");
        }

        protected void LinkThemNhanhLoaiVatTuThayThe_Click(object sender, EventArgs e)
        {
            OpenDialog("#ThemNhanhLoaiVatTuThayThe");
        }

        protected void LinkThemNhanhKyHieuLoaiVatTuThayThe_Click(object sender, EventArgs e)
        {
            OpenDialog("#ThemNhanhKyHieuLoaiVatTuThayThe");
        }

        protected void LinkThemNhanhQuocGia_Click(object sender, EventArgs e)
        {
            OpenDialog("#ThemNhanhQuocGia");
        }
        #endregion

        #region[Function]

        protected void BindGridDeNghiSuaChua()
        {
            if (txtDateBeGin.Text != "" && txtDateEnd.Text != "")
            {
                _dtDeNghiSuaChua = _clsDeNghiSuaChua.BindGirdTMRepair_Suggestion_FilterByDate(txtDateBeGin.Text, txtDateEnd.Text);
            }
            else if (drFilterSoXe.SelectedValue == "-1")
            {
                _dtDeNghiSuaChua = _clsDeNghiSuaChua.BindGirdTMRepair_Suggestion(txtSearch.Text);
            }
            else
            {
                _dtDeNghiSuaChua = _clsDeNghiSuaChua.BindGirdTMRepair_Suggestion_FilterSoXe(int.Parse(drFilterSoXe.SelectedValue));
            }
            
            if (_dtDeNghiSuaChua != null && _dtDeNghiSuaChua.Rows.Count > 0)
            {
                ListViewAll.DataSource = _dtDeNghiSuaChua;
                ListViewAll.DataBind();
                ListViewAll.Visible = true;
                DataPagerListAll.Visible = true;
            }
            else
            {
                ListViewAll.Visible = false;
                DataPagerListAll.Visible = false;
            }
        }

        protected void BindGridDeNghiSuaChuaEdit(int id)
        {
            _dtDeNghiSuaChuaEdit = _clsDeNghiSuaChua.BindGirdTMRepair_SuggestionDetail(id);
            if (_dtDeNghiSuaChuaEdit != null && _dtDeNghiSuaChuaEdit.Rows.Count > 0)
            {
                lbID.Text = _dtDeNghiSuaChuaEdit.Rows[0]["Repair_Suggestion_ID"].ToString();
                lbIDXoa.Text = _dtDeNghiSuaChuaEdit.Rows[0]["Repair_Suggestion_ID"].ToString();
                txtChungTu.Text = _dtDeNghiSuaChuaEdit.Rows[0]["Repair_Suggestion_Voucher"].ToString();
                txtNgay.Text = _dtDeNghiSuaChuaEdit.Rows[0]["Repair_Suggestion_Date"].ToString();
                drSoXe.SelectedValue = _dtDeNghiSuaChuaEdit.Rows[0]["Vehicle_ID"].ToString() == "" ? "-1" : _dtDeNghiSuaChuaEdit.Rows[0]["Vehicle_ID"].ToString();
                drTaiXe.SelectedValue = drSoXe.SelectedValue;
                drNhomXe.SelectedValue = drSoXe.SelectedValue;
                drLoaiVatTuThayThe.SelectedValue = _dtDeNghiSuaChuaEdit.Rows[0]["RepairMaterials_ID"].ToString() == "" ? "-1" : _dtDeNghiSuaChuaEdit.Rows[0]["RepairMaterials_ID"].ToString();
                drKyHieuLoaiVatTu.SelectedValue = _dtDeNghiSuaChuaEdit.Rows[0]["SymbolRepairMaterials_ID"].ToString() == "" ? "-1" : _dtDeNghiSuaChuaEdit.Rows[0]["SymbolRepairMaterials_ID"].ToString();
                drQuocGia.SelectedValue = _dtDeNghiSuaChuaEdit.Rows[0]["National_ID"].ToString() == "" ? "-1" : _dtDeNghiSuaChuaEdit.Rows[0]["National_ID"].ToString();
                txtSoLuong.Text = String.Format("{0:0}",_dtDeNghiSuaChuaEdit.Rows[0]["Repair_Suggestion_Quantity"]);
                txtDonGia.Text = String.Format("{0:0,00}",_dtDeNghiSuaChuaEdit.Rows[0]["Repair_Suggestion_Rate"]);
                txtChiPhi.Text = String.Format("{0:0,00 đ}",_dtDeNghiSuaChuaEdit.Rows[0]["Repair_Suggestion_Cost"]);
                txtGhiChu.Text = _dtDeNghiSuaChuaEdit.Rows[0]["Repair_Suggestion_Note"].ToString();
                drDuyet1.SelectedValue = _dtDeNghiSuaChuaEdit.Rows[0]["Repair_Suggestion_BrowseLv1"].ToString() == "" ? "-1" : _dtDeNghiSuaChuaEdit.Rows[0]["Repair_Suggestion_BrowseLv1"].ToString();
                drDuyet2.SelectedValue = _dtDeNghiSuaChuaEdit.Rows[0]["Repair_Suggestion_BrowseLv2"].ToString() == "" ? "-1" : _dtDeNghiSuaChuaEdit.Rows[0]["Repair_Suggestion_BrowseLv2"].ToString();
            }
        }

        protected void BindGridEmail(int id)
        {
            _dtDeNghiSuaChua = _clsDeNghiSuaChua.BindGirdTMRepair_SuggestionDetail(id);
            {
                if (_dtDeNghiSuaChua != null && _dtDeNghiSuaChua.Rows.Count > 0)
                {
                    lbIDDuyet.Text = _dtDeNghiSuaChua.Rows[0]["Repair_Suggestion_ID"].ToString();
                    txtEmailResive.Text = _dtDeNghiSuaChua.Rows[0]["Email_Receice1"].ToString();
                    if ((int)_dtDeNghiSuaChua.Rows[0]["Repair_Suggestion_Status"] == 0)
                    {
                        chkHide.Checked = true;
                    }
                    else
                    {
                        chkHide.Checked = false;
                    }
                }
            }
        }

        protected void BindGridDr()
        {
            DataTable dtXe = _clsXe.Search("");
            if (dtXe != null && dtXe.Rows.Count >0)
            {
                drSoXe.Items.Clear();
                drSoXe.Items.Add(new ListItem("--Vui lòng chọn số xe--","-1"));
                drSoXe.DataSource = dtXe;
                drSoXe.DataTextField = "Vehicle_Number";
                drSoXe.DataValueField = "Vehicle_ID";
                drSoXe.DataBind();

                drTaiXe.Items.Clear();
                drTaiXe.Items.Add(new ListItem("--Vui lòng chọn số xe--", "-1"));
                drTaiXe.DataSource = dtXe;
                drTaiXe.DataTextField = "M_FullNameMem";
                drTaiXe.DataValueField = "Vehicle_ID";
                drTaiXe.DataBind();

                drNhomXe.Items.Clear();
                drNhomXe.Items.Add(new ListItem("--Vui lòng chọn số xe--", "-1"));
                drNhomXe.DataSource = dtXe;
                drNhomXe.DataTextField = "VehicleGroup_Name";
                drNhomXe.DataValueField = "Vehicle_ID";
                drNhomXe.DataBind();

                drFilterSoXe.Items.Clear();
                drFilterSoXe.Items.Add(new ListItem("--Vui lòng chọn số xe--", "-1"));
                drFilterSoXe.DataSource = dtXe;
                drFilterSoXe.DataTextField = "Vehicle_Number";
                drFilterSoXe.DataValueField = "Vehicle_ID";
                drFilterSoXe.DataBind();
            }

            DataTable dtVatTuSuaChua = _clsVatTuSuaChua.Search("");
            if (dtVatTuSuaChua != null && dtVatTuSuaChua.Rows.Count > 0)
            {
                drLoaiVatTuThayThe.Items.Clear();
                drLoaiVatTuThayThe.Items.Add(new ListItem("--Vui lòng chọn vật tư sữa chữa--", "-1"));
                drLoaiVatTuThayThe.DataSource = dtVatTuSuaChua;
                drLoaiVatTuThayThe.DataTextField = "RepairMaterials_Name";
                drLoaiVatTuThayThe.DataValueField = "RepairMaterials_ID";
                drLoaiVatTuThayThe.DataBind();
            }

            DataTable dtLoaiVatTuSuaChua = _clsLoaiVatTuSuaChua.Search("");
            if (dtLoaiVatTuSuaChua != null && dtLoaiVatTuSuaChua.Rows.Count > 0)
            {
                drKyHieuLoaiVatTu.Items.Clear();
                drKyHieuLoaiVatTu.Items.Add(new ListItem("--Vui lòng chọn ký hiệu vật tư sữa chữa--", "-1"));
                drKyHieuLoaiVatTu.DataSource = dtLoaiVatTuSuaChua;
                drKyHieuLoaiVatTu.DataTextField = "SymbolRepairMaterials_Name";
                drKyHieuLoaiVatTu.DataValueField = "SymbolRepairMaterials_ID";
                drKyHieuLoaiVatTu.DataBind();
            }

            DataTable dtQuocGia = _clsQuocGia.Search("");
            if (dtQuocGia != null && dtQuocGia.Rows.Count > 0)
            {
                drQuocGia.Items.Clear();
                drQuocGia.Items.Add(new ListItem("--Vui lòng chọn quốc gia--", "-1"));
                drQuocGia.DataSource = dtQuocGia;
                drQuocGia.DataTextField = "TenQuocGia";
                drQuocGia.DataValueField = "STT";
                drQuocGia.DataBind();
            }
            DataTable dtDuyet1 = _clsPhongBan.BindGridMail("02");
            if (dtDuyet1 != null && dtDuyet1.Rows.Count > 0)
            {
                drDuyet1.Items.Clear();
                drDuyet1.Items.Add(new ListItem("--Chọn cấp độ duyệt cấp 1--", "-1"));
                drDuyet1.DataSource = dtDuyet1;
                drDuyet1.DataTextField = "Department_Name";
                drDuyet1.DataValueField = "Department_ID";
                drDuyet1.DataBind();
            }
            DataTable dtDuyet2 = _clsPhongBan.BindGridMail("01");
            if (dtDuyet2 != null && dtDuyet2.Rows.Count > 0)
            {
                drDuyet2.Items.Clear();
                drDuyet2.Items.Add(new ListItem("--Chọn cấp độ duyệt cấp 2--", "-1"));
                drDuyet2.DataSource = dtDuyet2;
                drDuyet2.DataTextField = "Department_Name";
                drDuyet2.DataValueField = "Department_ID";
                drDuyet2.DataBind();
            }
        }
        protected void BrowserNv()
        {
            try
            {
                if (chkHide.Checked == false)
                {
                    lbThongBaoLoi.Text = "Trạng thái của bạn đã được duyệt.Bạn không thể duyệt thêm lần nữa.Vui lòng chờ lãnh đạo xữ lý !";
                    OpenDialog("#thongbao");
                    updatePanelThongBao.Update();
                }
                else
                {
                    BrowserLd();
                    var obj = new clsTMRepair_SuggestionProperty
                    {
                        Repair_Suggestion_ID = int.Parse(lbIDDuyet.Text),
                        Repair_Suggestion_Status = 1
                    };
                    clsTMRepair_SuggestionBusiness.UpdateStatusTMRepair_Suggestion(obj);
                    lbThongBaoLoi.Text = "Bạn đã duyệt trạng thái thành công.Vui lòng chờ lãnh đạo xác nhận !";
                    OpenDialog("#thongbao");
                    updatePanelThongBao.Update();
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }

        //Insert
        protected void BrowserLd()
        {
            DataTable dtMailConfig = _clsMailConfig.BindGridMail();
            if (dtMailConfig != null && dtMailConfig.Rows.Count > 0)
            {
                SendMailDeNghiSuaChua(
                dtMailConfig.Rows[1]["TITILEMAIL"].ToString(),
                txtEmailResive.Text,
                dtMailConfig.Rows[1]["CONTENTMAIL"] +
                Environment.NewLine + Environment.NewLine +
                txtContent.Text +
                Environment.NewLine + "Link xét duyệt" +
                Environment.NewLine + dtMailConfig.Rows[1]["LINKACTIVE"] + lbIDDuyet.Text,
                dtMailConfig.Rows[1]["TITILEMAIL"].ToString(),
                dtMailConfig.Rows[1]["USERNAME"].ToString(),
                dtMailConfig.Rows[1]["PASSWORDS"].ToString());
            }
        }
        protected bool CheckInsert()
        {
            bool kiemtra = false;
            _dtDeNghiSuaChua = _clsDeNghiSuaChua.BindGirdTMRepair_Suggestion("");
            if (_dtDeNghiSuaChua != null && _dtDeNghiSuaChua.Rows.Count > 0)
            {
                foreach (DataRow dr in _dtDeNghiSuaChua.Rows)
                {
                    if (txtChungTu.Text == dr["Repair_Suggestion_Voucher"].ToString())
                    {
                        kiemtra = true;
                    }
                }
            }
            return kiemtra;
        }
        protected void Insert()
        {
            //Insert
            if (_flag)
            {
                InsertDeNghiSuaChua();
            }
            else //Update
            {
                UpdateDeNghiSuaChua();
            }
        }
        protected void InsertDeNghiSuaChua()
        {
            try
            {
                if (CheckInsert())
                {
                    lbThongBaoLoi.Text = "Mã Đề Nghị này đã tồn tại !";
                    OpenDialog("#thongbao");
                    updatePanelThongBao.Update();
                }
                else
                {
                    var obj = new clsTMRepair_SuggestionProperty
                    {
                        Repair_Suggestion_Voucher = txtChungTu.Text,
                        Repair_Suggestion_Date = Convert.ToDateTime(txtNgay.Text),
                        Vehicle_ID = drSoXe.SelectedValue != "-1" ? (int?)Convert.ToInt32(drSoXe.SelectedValue) : null,
                        RepairMaterials_ID = drLoaiVatTuThayThe.SelectedValue != "-1" ? (float?)float.Parse(drLoaiVatTuThayThe.SelectedValue) : null,
                        SymbolRepairMaterials_ID = drKyHieuLoaiVatTu.SelectedValue != "-1" ? (float?)float.Parse(drKyHieuLoaiVatTu.SelectedValue) : null,
                        National_ID = drQuocGia.SelectedValue != "-1" ? (float?)float.Parse(drQuocGia.SelectedValue) : null,
                        Repair_Suggestion_Quantity = float.Parse(txtSoLuong.Text),
                        Repair_Suggestion_Rate = float.Parse(txtDonGia.Text),
                        Repair_Suggestion_Cost = float.Parse(txtSoLuong.Text) * float.Parse(txtDonGia.Text),
                        Repair_Suggestion_Note = txtGhiChu.Text,
                        Repair_Suggestion_BrowseLv1 = drDuyet1.SelectedValue != "-1" ? (int?)int.Parse(drDuyet1.SelectedValue) : null,
                        Repair_Suggestion_BrowseLv2 = drDuyet2.SelectedValue != "-1" ? (int?)int.Parse(drDuyet2.SelectedValue) : null
                    };
                    clsTMRepair_SuggestionBusiness.InsertTMRepair_Suggestion(obj);
                    lbThongBaoLoi.Text = "Thêm mới thành công mẫu tin !";
                    OpenDialog("#thongbao");
                    updatePanelThongBao.Update();
                    BindGridDeNghiSuaChua();
                    ClearTextbox();
                    txtChungTu.Text = "MT000" + MaTuDong();
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }

        protected void UpdateDeNghiSuaChua()
        {
            try
            {
                var obj = new clsTMRepair_SuggestionProperty
                {
                    Repair_Suggestion_ID = Convert.ToInt32(lbID.Text),
                    Repair_Suggestion_Voucher = txtChungTu.Text,
                    Repair_Suggestion_Date = Convert.ToDateTime(txtNgay.Text),
                    Vehicle_ID = drSoXe.SelectedValue != "-1" ? (int?)Convert.ToInt32(drSoXe.SelectedValue) : null,
                    RepairMaterials_ID = drLoaiVatTuThayThe.SelectedValue != "-1" ? (float?)float.Parse(drLoaiVatTuThayThe.SelectedValue) : null,
                    SymbolRepairMaterials_ID = drKyHieuLoaiVatTu.SelectedValue != "-1" ? (float?)float.Parse(drKyHieuLoaiVatTu.SelectedValue) : null,
                    National_ID = drQuocGia.SelectedValue != "-1" ? (float?)float.Parse(drQuocGia.SelectedValue) : null,
                    Repair_Suggestion_Quantity = float.Parse(txtSoLuong.Text),
                    Repair_Suggestion_Rate = float.Parse(txtDonGia.Text),
                    Repair_Suggestion_Cost = float.Parse(txtSoLuong.Text) * float.Parse(txtDonGia.Text),
                    Repair_Suggestion_Note = txtGhiChu.Text,
                    Repair_Suggestion_BrowseLv1 = drDuyet1.SelectedValue != "-1" ? (int?)int.Parse(drDuyet1.SelectedValue) : null,
                    Repair_Suggestion_BrowseLv2 = drDuyet2.SelectedValue != "-1" ? (int?)int.Parse(drDuyet2.SelectedValue) : null
                };
                clsTMRepair_SuggestionBusiness.UpdateTMRepair_Suggestion(obj);
                lbThongBaoLoi.Text = "Cập nhật thành công mẫu tin !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
                BindGridDeNghiSuaChuaEdit(int.Parse(lbID.Text));
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }

        //Search
        protected void Search(string keywords)
        {
            _dtSearch = _clsDeNghiSuaChua.BindGirdTMRepair_Suggestion(txtSearch.Text);
            if (_dtSearch != null && _dtSearch.Rows.Count > 0)
            {
                ListViewAll.DataSource = _dtSearch;
                ListViewAll.DataBind();
                ListViewAll.Visible = true;
                DataPagerListAll.Visible = true;

                StrAlert += "<div class='alert alert-success'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Tìm thấy " + _dtSearch.Rows.Count + " mẫu tin !";
                StrAlert += "</div>";
            }
            else
            {
                ListViewAll.Visible = false;
                DataPagerListAll.Visible = false;
                StrAlert += "<div class='alert alert-error'>";
                StrAlert += "<a href='#' class='close' data-dismiss='alert'>&times;</a>";
                StrAlert += "Không tìm thấy mẫu tin nào !";
                StrAlert += "</div>";
            }
        }

        //Filter
        protected void FilterSoXe()
        {
            
        }

        //Autocomplete
        protected void Autocomplete()
        {
            _dtAutoComplete = _clsDeNghiSuaChua.BindGirdTMRepair_Suggestion("");
            if (_dtAutoComplete != null && _dtAutoComplete.Rows.Count > 0)
            {
                foreach (DataRow dr in _dtAutoComplete.Rows)
                {
                    if (string.IsNullOrEmpty(SuggestionList))
                    {
                        SuggestionList += "\"" + dr["Repair_Suggestion_Voucher"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["FullNameMem"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["VehicleGroup_Name"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["RepairMaterials_Name"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["SymbolRepairMaterials_Name"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["National_Name"].ToString().Replace("\n", " ") + "\",";
                    }
                    else
                    {
                        SuggestionList += "\"" + dr["Repair_Suggestion_Voucher"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["FullNameMem"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["VehicleGroup_Name"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["RepairMaterials_Name"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["SymbolRepairMaterials_Name"].ToString().Replace("\n", " ") + "\",";
                        SuggestionList += "\"" + dr["National_Name"].ToString().Replace("\n", " ") + "\",";
                    }
                }
            }
        }

        #endregion

        #region[MaTangTuDong]

        protected int MaTuDong()
        {
            int i = 0;
            _dtDeNghiSuaChua = _clsDeNghiSuaChua.BindGirdTMRepair_Suggestion("");
            if (_dtDeNghiSuaChua != null && _dtDeNghiSuaChua.Rows.Count > 0)
            {
                int max = Convert.ToInt32(_dtDeNghiSuaChua.Rows[0]["Repair_Suggestion_ID"].ToString());
                for (i = 0; i < _dtDeNghiSuaChua.Rows.Count; i++)
                {
                    if (int.Parse(_dtDeNghiSuaChua.Rows[i]["Repair_Suggestion_ID"].ToString()) > max)
                    {
                        max = Convert.ToInt32(_dtDeNghiSuaChua.Rows[i]["Repair_Suggestion_ID"].ToString());
                    }
                }
                i = max + 1;
            }
            return i;
        }

        #endregion

        #region[ClearTextBox]

        protected void ClearTextbox()
        {
            drDuyet1.SelectedIndex = -1;
            drDuyet2.SelectedIndex = -1;
            txtGhiChu.Text = "";
            txtChiPhi.Text = "";
            txtDonGia.Text = "";
            txtSoLuong.Text = "";
            drQuocGia.SelectedIndex = -1;
            drKyHieuLoaiVatTu.SelectedIndex = -1;
            drLoaiVatTuThayThe.SelectedIndex = -1;
            drTaiXe.SelectedIndex = -1;
            drSoXe.SelectedIndex = -1;
            txtNgay.Text = "";
            txtChungTu.Text = "";
        }

        #endregion

        #region[OpenDialog]

        private void OpenDialog(string dialogId)
        {
            var sb = new StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('open');");
            ScriptManager.RegisterStartupScript(Page, Page.GetType(),
                "scriptKey", sb.ToString(), true);
        }

        private void CloseDialog(string dialogId)
        {
            var sb = new StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('close');");
            ScriptManager.RegisterStartupScript(Page, Page.GetType(),
                "scriptKey", sb.ToString(), true);
        }

        #endregion

        #region[SendMail]
        private void SendMailDeNghiSuaChua(string titileFrom, string from, string conten, string subject, string username, string password)
        {
            var smtpServer = new SmtpClient
            {
                Credentials = new System.Net.NetworkCredential(username, password),
                Port = 587,
                Host = "smtp.gmail.com",
                EnableSsl = true
            };
            var mail = new MailMessage();
            String[] addr = from.Split(',');
            try
            {
                mail.From = new MailAddress(username,
                titileFrom, Encoding.UTF8);
                Byte i;
                for (i = 0; i < addr.Length; i++)
                    mail.To.Add(addr[i]);

                mail.Subject = subject;
                mail.Body = conten;

                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                mail.ReplyToList.Add(new MailAddress(from));
                smtpServer.Send(mail);
                lbThongBaoLoi.Text = "Hệ thống đã gửi thông tin xét duyệt vào mail của " + txtEmailResive.Text;
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = "Có lỗi xảy ra trong quá trình xét duyệt !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();

                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        #endregion

        #region[Permisstion]
        protected void CheckPermisstion()
        {
            HttpCookie cookie = Request.Cookies["UserLogin"];
            if (cookie != null)
            {
                bool Is_Page_All = SecurityServices.HasPermisstionPage(StringContent.QuanLySuaChuaThayThe, int.Parse(cookie["RolesID"]), true);
                if (Is_Page_All == true)
                {
                    bool AddNew = SecurityServices.HasPermisstion(StringContent.QuanLySuaChuaThayThe, int.Parse(cookie["RolesID"]), TypeaAudit.AddNew);
                    if (AddNew == false)
                    {
                        cmdAddNew.Visible = false;
                    }
                    else
                    {
                        cmdAddNew.Visible = true;
                    }
                    bool Edit = SecurityServices.HasPermisstion(StringContent.QuanLySuaChuaThayThe, int.Parse(cookie["RolesID"]), TypeaAudit.Edit);
                    if (Edit == false)
                    {
                        cmdEdit.Visible = false;
                    }
                    else
                    {
                        cmdEdit.Visible = true;
                    }
                    bool Del = SecurityServices.HasPermisstion(StringContent.QuanLySuaChuaThayThe, int.Parse(cookie["RolesID"]), TypeaAudit.Delete);
                    if (Del == false)
                    {
                        cmdDel.Visible = false;
                    }
                    else
                    {
                        cmdDel.Visible = true;
                    }
                }
                else
                {
                    Response.Redirect("error-page.aspx");
                }
            }
        }
        #endregion
    }
}